package juc.tools;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @Package juc.tools
 * @ClassName ForkJoinTest
 * @Description
 * @Author yangxin
 * @Email yangxin_xy@189.com
 * @Date 2022/2/3 21:43
 */


public class ForkJoinTest
{
    public static void main(String[] args) throws Exception
    {
        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        ForkJoinTask task = new ForkJoinTask(1, 100);
        java.util.concurrent.ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(task);
        int result = forkJoinTask.get();
        System.out.println(result);
        forkJoinPool.shutdown();
    }
}

class ForkJoinTask extends RecursiveTask<Integer>
{

    private Integer start;
    private Integer end;
    private Integer middle = 2;

    public ForkJoinTask(Integer start, Integer end)
    {
        super();
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute()
    {
        Integer sum = 0;
        boolean flag = (end - start) < middle;
        if (flag)
        {
            for (int i = start; i <= end; i++)
            {
                sum += i;
            }
        }
        else
        {
            this.middle = (end + start) / 2;
            ForkJoinTask task1 = new ForkJoinTask(start, middle);
            ForkJoinTask task2 = new ForkJoinTask(middle + 1, end);
            task1.fork();
            task2.fork();
            sum = task1.join() + task2.join();
        }
        return sum;
    }
}

